import axios from 'axios'
import router from '@/router'

const server = axios.create({
  baseURL: import.meta.env.VITE_BASE_API // import.meta.env.PROD
  // withCredentials: true
})

// Axios 无感知刷新令牌，参考 https://www.dashingdog.cn/article/11 与 https://segmentfault.com/a/1190000020210980 实现

/**
 * 请求拦截器
 */
server.interceptors.request.use(
  (config) => {
    config.headers.Authorization = 'Bearer ' + localStorage.getItem('token')
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

/**
 * 响应拦截器
 */
server.interceptors.response.use(
  (response) => {
    return response.data
  },
  (error) => {
    switch (error.response.status) {
      case 401:
        if (document.getElementsByClassName('el-message').length === 0) {
          console.log('会话已过期，请重新登录')
        }
        router.push({ name: 'login' })
        break
      case 422:
        if (document.getElementsByClassName('el-message').length === 0) {
          console.log('有错误')
        }
        break
      case 403:
        if (document.getElementsByClassName('el-message').length === 0) {
          console.log('无权限')
        }
        break
      case 404:
        if (document.getElementsByClassName('el-message').length === 0) {
          console.log('资源不存在')
        }
        break
      case 500:
        if (document.getElementsByClassName('el-message').length === 0) {
          console.log('服务器错误')
        }
        break
    }
    return Promise.reject(error)
  }
)

export default server
